/*
 * @Author: fishroom
 * @Date: 2022-09-27 17:31:06
 * @LastEditTime: 2023-01-03 10:49:03
 * @FilePath: \koa\app\controller\AdminController.ts
 */
import { Context, Next } from "koa";
import UserServer from "../server/UserServer";
import { sign } from "../util/webToken";
import md5 from "md5";
import response from "../util/response";
import validate from "../util/validate";
import { Rules } from "async-validator";
// import client from "./../util/redis";
class AdminController {
  // 获取列表
  async index(ctx: Context) {
    const getUser = await UserServer.getUser();
    ctx.body = response.success({ list: getUser });
  }
// 更新用户
  async updaUser(ctx: Context) {
    let newUser = ctx.request.body;
    newUser.password = md5(newUser.password as string);
    const data = await UserServer.updataUserById(newUser);

    ctx.body = data;
  }
  // 登录
  async LoginAdmin(ctx: Context) {
    const rules: Rules = {
      username: [
        {
          type: "string",
          required: true,
          message: "用户名不能为空",
        },
      ],
      password: [
        {
          type: "string",
          required: true,
          message: "密码不能为空",
        },
      ],
    };
    interface IAdmin {
      username: string;
      password: string;
    }

    var captcha = ctx.cookies.get("sessionId");
    // 还原 base 64 字符串
    captcha = Buffer.from(captcha as string, "base64").toString();
    if (ctx.request.body.captcha.toUpperCase() != JSON.parse(captcha).sessionId.toUpperCase())
      return response.CxtError(ctx, "验证码错误");
    const { data, err } = await validate<IAdmin>(ctx, rules);
    if (err !== null) {
      return response.CxtError(ctx, err.errors[0].message);
    }
    data.password = md5(data.password);
    const { admin, error } = await UserServer.LoginAdmin(data);
    if (error != null || admin == null) {
      return (ctx.body = response.error("账号或密码错误", { error }, 4000));
    }
    let token = sign(admin);
    // client.set(admin.username, admin);
    ctx.body = response.success({ token }, "登陆成功");
  }
}

export default new AdminController();
